import {
    getItems,
    getItems2,
    getAdressManagesAPI,
    getAdressManagesAPI2,
    postWxAppPay,
    postAlipay,
    createOrder,
    postAlipay2,
    myCouponLists,
    couponWriteoff,
    moneyAndScroePay,
    getuserInfo,
    getYiPayStatu,
    toYiPay,
    payUseLastMoney,
    setPassWd,
    getPayPass
} from "@/api/api";
import { isShowPayType } from "@/api/areaApi";
import moment from 'moment';
const config = {
    headers:{
        'Authorization': localStorage.getItem("token"),
        'token': localStorage.getItem("token")
    }
};

import {
    Toast
} from "vant";
const payMixin = {
    data() {
        return {
            payStatus: false,
            shareUser: {},
            is_pay_pass:"0",
            showPayType: {}
        }
    },
    created() {
        this.getPay()
        this.getUserData()
        this.getPayType()
        this.getPayPass()
    },
    computed: {
        time7_21() {
            console.log(moment('07:00:00').hour)
            let is_time = moment().hour.isBetween(moment('07:00:00').hour, moment('21:00:00').hour)
            console.log(is_time)
            return is_time
        }
    },
    methods: {
        // 获得支付方式
        getPayType(){
            isShowPayType().then((result) => {
                this.showPayType = result.data.data
                console.log(this.showPayType)
            }).catch((err) => {

            });
        },
        getPayPass(){
            //获取支付密码设置
            getPayPass().then((res) => {
                console.log("getPayPass", res);
                if (res.data.code == 1) {
                    this.is_pay_pass = res.data.data.is_pay_pass;
                    console.log("is_pay_pass",this.is_pay_pass);
                }
            });
        },
        // 获取用户信息
        getUserData() {
            let urls = `${localStorage.getItem("share_weixin_shareurl")}/api/share/getuser`
            this.$axios.post(urls,{ wallet_type: "mutual" },config).then(res=>{
                if(res.data.code == 1){
                    this.shareUser = res.data.data;
                }else{
                    this.$dialog.alert({
                        message:res.data.msg
                    })
                }
            })
        },
        // 余额充值
        toRecharge() {
            this.$router.push('/recharge')
        },
        // 获取夜间支付状态
        getPay() {
            getYiPayStatu().then(res => {
                // this.payStatus = res.data.data.status
            })
        },
        // 选择提货券
        use() {
            let that = this
            if (this.arr.some((ele) => ele.check)) {
                console.log("选择提货券", this.order_sn);
                if (this.order_sn != null || this.order_sn != undefined) {
                    this.show = false;
                    this.selFlag = 3;
                    this.$dialog.alert({
                        title: '提货券兑换',
                        message: '亲，您确定要使用提货券进行兑换吗？',
                        showCancelButton: true
                    }).then((result) => {
                        this.pay();
                        return;
                    }).catch((err) => {});
                } else {
                    this.show = false;
                    this.selFlag = 3;
                    createOrder({
                        from: "goods",
                        address_id: this.addressDetail.id,
                        coupons_id: 0,
                        order_type: "goods",
                        buy_type: "alone",
                        groupon_id: 0,
                        one_day: this.one_day,
                        goods_list: [{
                            goods_id: this.details.id,
                            goods_num: 1,
                            sku_price_id: this.$route.params["fromPath"] == 'shop' ? this.details.sku[0].id : this.details.sku_price[0].id,
                            goods_price: this.details.price,
                            goods_type: "2",
                            activity_type: "",
                            dispatch_type: "express",
                        }, ],
                    }).then(res => {
                        Toast(res.data.msg)
                        if (res.data.code == 1) {
                            that.order_sn = res.data.data.order_sn;
                            this.$dialog.alert({
                                title: '提货券兑换',
                                message: '亲，您确定要使用提货券进行兑换吗？',
                                showCancelButton: true
                            }).then((result) => {
                                this.pay();
                            }).catch((err) => {});
                        }else{

                        }
                    })
                }
            } else {
                this.$dialog.alert({
                    message: "未选择",
                });
            }
        },
        //支付
        pay() {
            console.log(this.selFlag );
            var that = this;
            if (this.addressDetail == null) {
                that.LOADING = false;
                this.$dialog
                    .alert({
                        message: "您还没有收货地址噢，请填写",
                    })
                    .then(() => {
                        this.$router.push("/receiptList");
                        // this.$router.push({
                        //     name: "add",
                        //     params: this.$route.params
                        // });
                    });
                return;
            }
            if (this.selFlag == 0) {
                this.LOADING = false;
                this.$dialog.alert({
                    message: "支付方式未选择",
                });
                return;
            }


            //判断支付密码是否正确输入
           console.log("is_pay_pass",this.is_pay_pass);
            if(!this.payPassWordConfirm&&this.selFlag != 8&&this.is_pay_pass == 1){
                this.payPassWordShow = true;
                if(this.payPassWordIs){
                    this.showKeyboard = true
                }
                return;
            }else{
                this.payPassWordConfirm = false;
                this.payPassWordInfo = "";
            }

            if (this.selFlag == 1) {
                var type = "";
                if (this.selFlag == 2) {
                    type = "alipay";
                }
                if (this.selFlag == 1) {
                    type = "wechat";
                    // Toast("暂不支持");
                    // return;
                }
                this.LOADING = true;
                if (this.has_order) {
                    postAlipay2({
                            order_sn: that.order_sn,
                            type: type
                        })
                        .then((res) => {
                            console.log("postAlipay2", res);
                            if (res.data.code == 1) {
                                // window.location.href = res.data.data.url;
                                var url = res.data.data.url;
                                try {
                                    window.JS_TROOPS.alipay(url);
                                } catch (e) {
                                    this.$router.push("/upgradeTips");
                                }
                            } else {
                                this.$dialog
                                    .alert({
                                        message: res.data.msg,
                                    })
                                    .then((res) => {
                                        this.$router.go(-1);
                                    });
                            }
                        })
                        .error((res) => {
                            console.log("error", res);
                        });
                } else {
                    createOrder({
                        from: "goods",
                        address_id: this.addressDetail.id,
                        coupons_id: 0,
                        order_type: "goods",
                        buy_type: "alone",
                        groupon_id: 0,
                        one_day: this.one_day,
                        goods_list: [{
                            goods_id: this.details.id,
                            goods_num: 1,
                            sku_price_id: this.$route.params["fromPath"] == 'shop' ? this.details.sku[0].id : this.details.sku_price[0].id,
                            goods_price: this.details.price,
                            goods_type: "2",
                            activity_type: "",
                            dispatch_type: "express",
                        }, ],
                    }).then((res) => {
                        console.log("2");
                        this.LOADING = false;
                        console.log(res);
                        if (res.data.code == 1) {
                            that.order_sn = res.data.data.order_sn;
                            let strData = "";
                            that.splitShow = true
                            postAlipay2({
                                    order_sn: that.order_sn,
                                    type: 'wechat'
                                })
                                .then((res) => {
                                    console.log("postAlipay2", res);
                                    if (res.data.code == 1) {
                                        // window.location.href=res.data.data.url;
                                        var url = res.data.data.url;
                                        try {
                                            window.JS_TROOPS.alipay(url);
                                        } catch (e) {
                                            this.$router.push("/upgradeTips");
                                        }
                                    } else if (res.data.code == 0 && type == 'alipay') {
                                        this.$dialog
                                            .alert({
                                                title: "支付",
                                                message: "亲，还没有开通本地支付宝商户，请点击确定，可选择本地微信支付！",
                                                confirmButtonText: "确定支付",
                                            })
                                            .then((res) => {
                                                this.$router.push({
                                                    name: "qrCodePay",
                                                    params: {
                                                        order_sn: this.order_sn
                                                    },
                                                });
                                            });
                                    } else if (res.data.code == 0 && type == 'wechat') {
                                        this.toQrCodePay();
                                    } else if (res.data.code == 2) {
                                        this.$dialog
                                            .alert({
                                                title: "提示",
                                                message: res.data.msg,
                                                confirmButtonText: "确定",
                                            })
                                    }
                                })
                                .error((res) => {
                                    console.log("error", res);
                                });
                        } else {
                            this.LOADING = false;
                            this.$dialog
                                .alert({
                                    message: res.data.msg,
                                })
                                .then((result) => {
                                    this.$router.push({
                                        name: "orders",
                                        params: {
                                            typeNum: 0
                                        }
                                    });
                                })
                                .catch((err) => {});
                        }
                    });
                }
            }
            if (this.selFlag == 3) {
                if (this.checkedId == 0) {
                    this.$dialog.alert({
                        message: "提货券未选择",
                    });
                }
                this.LOADING = true;
                couponWriteoff({
                    order_sn: this.order_sn,
                    code_id: this.checkedId,
                    goods_id: this.details.id,
                    total_price: this.details.price,
                    address_id: this.addressDetail.id,
                    one_day: this.one_day,
                }).then((res) => {
                    this.LOADING = false;
                    console.log("getAdressMcouponWriteoffanagesAPI2", res);
                    if (res.data.code == 1) {
                        this.$dialog
                            .alert({
                                message: "购买成功",
                            })
                            .then((res) => {
                                // this.$router.push({
                                //     name: "index"
                                // });
                                this.$router.go(-1)
                            });
                    } else {
                        this.$dialog
                            .alert({
                                message: res.data.msg,
                            })
                            .then((res) => {
                                this.$router.go(-1);
                            });
                    }
                });
            }
            if (this.selFlag == 8) {
                // this.creatOrders("wallet");
                createOrder({
                    from: "goods",
                    address_id: this.addressDetail.id,
                    coupons_id: 0,
                    order_type: "goods",
                    buy_type: "alone",
                    groupon_id: 0,
                    one_day: this.one_day,
                    goods_list: [{
                        goods_id: this.details.id,
                        goods_num: 1,
                        sku_price_id: this.$route.params["fromPath"] == 'shop' ? this.details.sku[0].id : this.details.sku_price[0].id,
                        goods_price: this.details.price,
                        goods_type: "2",
                        activity_type: "",
                        dispatch_type: "express",
                    }, ],
                }).then(res => {
                    console.log("3");
                    if (res.data.code == 1) {
                        this.order_sn = res.data.data.order_sn;
                        this.$router.push({
                            name: 'payForMe',
                            params: {
                                order_sn: this.order_sn,
                                id: this.details.id,
                            }
                        })
                    }else{
                        Toast(res.data.msg)
                    }
                })

            }
            if (this.selFlag == 6) {
                this.creatOrders("score");
            }
            if (this.selFlag == 7 || this.selFlag == 10 || this.selFlag == 20 || this.selFlag==30) {
                if (this.has_order) {
                    payUseLastMoney({
                        order_sn: that.order_sn,
                        payment: "wallet",
                        is_old: that.is_old
                    }).then(result => {
                        if (result.data.code == 1) {
                            this.$dialog.alert({
                                message: '购买成功',
                            }).then((result) => {
                                this.backHandler()
                            }).catch((err) => {});
                        } else {
                            this.$dialog.alert({
                                message: result.data.msg,
                            }).then((result) => {}).catch((err) => {});
                        }
                    })
                } else {
                    createOrder({
                        from: "goods",
                        address_id: this.addressDetail.id,
                        coupons_id: 0,
                        order_type: "goods",
                        buy_type: "alone",
                        groupon_id: 0,
                        one_day: this.one_day,
                        goods_list: [{
                            goods_id: this.details.id,
                            goods_num: 1,
                            sku_price_id: this.$route.params["fromPath"] == 'shop' ? this.details.sku[0].id : this.details.sku_price[0].id,
                            goods_price: this.details.price,
                            goods_type: "2",
                            activity_type: "",
                            dispatch_type: "express",
                        }, ],
                    }).then(res => {
                        if (res.data.code == 1) {
                            that.order_sn = res.data.data.order_sn;
                            payUseLastMoney({
                                order_sn: that.order_sn,
                                payment: type,
                                yg: this.xfj ? 1 : 0,
                                is_old: that.is_old
                            }).then(result => {
                                if (result.data.code == 1) {
                                    this.$dialog.alert({
                                        message: '购买成功',
                                    }).then((result) => {
                                        this.backHandler()
                                    }).catch((err) => {});
                                } else {
                                    this.$dialog.alert({
                                        message: result.data.msg,
                                    }).then((result) => {}).catch((err) => {});
                                }
                            })
                        }else{
                            Toast(res.data.msg)
                        }
                    })
                }
            }
            if(this.selFlag == 21){
                if (this.has_order) {
                    payUseLastMoney({
                        order_sn: that.order_sn,
                        payment: "mutual",
                        yg: this.xfj ? 1 : 0,
                        is_old: that.is_old
                    }).then(result => {
                        if (result.data.code == 1) {
                            this.$dialog.alert({
                                message: '购买成功',
                            }).then((result) => {
                                this.backHandler()
                            }).catch((err) => {});
                        } else {
                            this.$dialog.alert({
                                message: result.data.msg,
                            }).then((result) => {}).catch((err) => {});
                        }
                    })
                } else {
                    createOrder({
                        from: "goods",
                        address_id: this.addressDetail.id,
                        coupons_id: 0,
                        order_type: "goods",
                        buy_type: "alone",
                        groupon_id: 0,
                        one_day: this.one_day,
                        goods_list: [{
                            goods_id: this.details.id,
                            goods_num: 1,
                            sku_price_id: this.$route.params["fromPath"] == 'shop' ? this.details.sku[0].id : this.details.sku_price[0].id,
                            goods_price: this.details.price,
                            goods_type: "2",
                            activity_type: "",
                            dispatch_type: "express",
                        }, ],
                    }).then(res => {
                        if (res.data.code == 1) {
                            that.order_sn = res.data.data.order_sn;
                            payUseLastMoney({
                                order_sn: that.order_sn,
                                payment: "mutual",
                                is_old: that.is_old
                            }).then(result => {
                                if (result.data.code == 1) {
                                    this.$dialog.alert({
                                        message: '购买成功',
                                    }).then((result) => {
                                        this.backHandler()
                                    }).catch((err) => {});
                                } else {
                                    this.$dialog.alert({
                                        message: result.data.msg,
                                    }).then((result) => {}).catch((err) => {});
                                }
                            })
                        }else{
                            Toast(res.data.msg)
                        }
                    })
                }
            }
        },
        async paySel(val) {
            this.payPassWord="";
            //判断支付密码是否正确输入
            // if(!this.payPassWordConfirm){
            //     this.payPassWordShow = true;
            //     return;
            // }
            if (this.addressDetail == null) {
                this.LOADING = false;
                this.$dialog
                    .alert({
                        message: "您还没有收货地址噢，请填写",
                    })
                    .then(() => {
                        this.$router.push("/receiptList");
                    });
                return;
            }
            if (val != 20) {
                this.xfj = false
            }
            if (val == 1) {
                // Toast("暂不支持");
                // await this.creatOrderWeixinAli();
                // this.toQrCodePay();
                // return;
                this.selFlag = 1;
            } else if (val == 2) {
                this.selFlag = 2;
            } else if (val === 3) {
                console.log(this.arr);

                if (this.arr.length) {
                    // this.selFlag = 3
                    // this.$dialog.alert({
                    //   title:'提货券兑换',
                    //   message:'亲，您确定要使用提货券进行兑换吗？',
                    //   showCancelButton:true
                    // }).then((result) => {
                    //   this.show = true;
                    // }).catch((err) => {

                    // });
                    this.show = true;

                } else {
                    this.$dialog.alert({
                        message: "未能找到可以使用的提货券",
                    });
                }
            } else if (val === 4) {
                this.selFlag = 4;
                // goods_id:this.details.id,
                // total_price:this.details.price,
                // address_id:this.addressDetail.id
                this.$router.push({
                    name: "luorderNo",
                    params: {
                        goods_id: this.details.id,
                        total_price: this.details.price,
                        address_id: this.addressDetail.id,
                    },
                });
            } else if (val == 8) {
                console.log("现金");
                this.selFlag = 8;

            } else if (val == 6) {
                this.selFlag = 6;
            } else if (val == 7) {
                this.selFlag = 7;
                this.is_old = 0
            } else if (val == 10) {
                this.selFlag = 10;
                this.is_old = 1
            } else if (val == 20) {
                this.selFlag = 20;
                this.is_old = 2
                if(this.details.one_day==2){
                    this.xfj = true
                }
            }else if (val == 21) {
                this.selFlag = 21;
            }else if(val == 30){
                this.is_old = 3
                this.selFlag = 30
            }
        },
        //获取数据地址
        init() {
            var addressId = this.$wweixin.getItem("addressId");

            getAdressManagesAPI2().then((res) => {
                console.log("getAdressManagesAPI2", res);
                let addressList = res.data.data;
                if (addressList.length > 0) {
                    for (const address of addressList) {
                        if (address.id == parseInt(addressId)) {
                            this.addressDetail = address;
                            localStorage.removeItem("addressId");
                            return;
                        } else if (address.is_default == 1) {
                            this.addressDetail = address;
                            return;
                        }
                    }
                } else {
                    this.addressDetail = addressList[0];
                    return;
                }
            });
        },
        //添加收货地址
        add() {
            console.log("add");
            // this.$router.push("/add");
            this.$router.push({
                name: "add",
                params: this.$route.params
            });
        },
        //修改收货地址
        edit() {
            console.log("edit");
            this.$router.push("/receiptList");
        },
         //设置支付密码
         toSetPayPassword() {
            this.$router.push("/payPassword");
        },
        getPayPassWord(){
            setPassWd({
                      event: "info",
                  }).then(res => {
                      console.log("getPayPassWord", res);
                      if(res.data.code == 1){
                         this.payPassWordIs = true;
                      }else{
                        this.payPassWordIs = false;
                      }
                  })
          },
        onBlurEvent() {
            console.log("onBlurEvent")
            if(this.payPassWord!=""){

            }
        },
        onPayPassWordInput(event) {
            console.log("onPayPassWordInput")
            console.log(event, this.payPassWord);
            if (this.payPassWord.length == 3) {
                this.showKeyboard = false;
                this.payPassWord=this.payPassWord+""+event
                this.confirmPassWd();
            }
        },
        closePayPassWordShow(){
            console.log("closePayPassWordShow");
            this.showKeyboard = false
        },
        confirmPassWd() {

            setPassWd({
                event: "confirm",
                pwd: this.payPassWord,
            }).then(res => {
                console.log("confirmPassWd", res);
                this.payPassWord="";
                if(res.data.code == 1){
                    this.showKeyboard = false
                    this.payPassWordConfirm = true
                    this.payPassWordShow = false
                    this.pay();
                }else{

                    this.showKeyboard = false
                    this.payPassWord="";
                    this.payPassWordInfo=res.data.msg;
                    var msg=res.data.msg;
                    console.log("msg.indexOf", msg.indexOf("0次"));
                    if(msg.indexOf("0次")!= -1 || msg.indexOf("次数过多")!= -1){
                           this.payPassWordIs=false;
                           this.payPassWordTitle="支付失败";
                           this.payPassWordCenter="支付密码输入错误次数过多，请3个小时后再进行设置"
                    }else{
                        Toast(res.data.msg)
                    }

                }
            })
        }
    }
}

export default payMixin
